package com.brillilab.service.core.system.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.brillilab.common.constant.SystemConfigConstant;
import com.brillilab.common.utils.ValidatorUtil;
import com.brillilab.dao.mapper.system.SystemConfigMapper;
import com.brillilab.domain.po.system.SystemConfig;
import com.brillilab.service.core.system.ISystemConfigService;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 * 系统配置表 服务实现类
 * </p>
 *
 * @author zlb
 * @since 2019-10-09
 */
@Service
public class SystemConfigServiceImpl extends ServiceImpl<SystemConfigMapper, SystemConfig> implements ISystemConfigService {

    @Resource
    private SystemConfigMapper systemConfigMapper;

    @Override
    public SystemConfig insert(SystemConfig entity) {
        Integer insert = systemConfigMapper.insert(entity);
        Assert.isTrue(insert == 1, "添加失败");
        return entity;
    }

    @Override
    public boolean deleteById(Long id) {
        Integer b = systemConfigMapper.deleteById(id);
        return b == 1 ? true : false;
    }

    @Override
    public SystemConfig selectByCode(String code) {
        return systemConfigMapper.selectOne(new LambdaQueryWrapper<SystemConfig>().eq(SystemConfig::getCode, code));
    }

    @Override
    public boolean updateById(SystemConfig entity) {
        Integer b = systemConfigMapper.updateById(entity);
        return b == 1 ? true : false;
    }

    @Override
    public SystemConfig selectById(Long id) {
        return systemConfigMapper.selectById(id);
    }

    @Override
    public boolean checkEmailFormat(String email) {
        Assert.isTrue(ValidatorUtil.isEmail(email), "邮箱格式错误！");
        String[] emailArr = email.split("@");
        String emailSuffix = emailArr.length == 2 ? emailArr[1].toLowerCase() : "";
        //判断邮箱后缀是否为学术机构邮箱，是则免审通过申请，否则进入待审核
        SystemConfig systemConfig = selectByCode(SystemConfigConstant.EMAIL_SUFFIX);
        List<String> learningEmailSuffixList = JSONObject.parseArray(systemConfig.getValue(),String.class);
        boolean isRightEmail = false;
        for (String suffix : learningEmailSuffixList) {
            if (emailSuffix.contains(suffix)) {
                //包含学术邮箱后缀，允许提交
                isRightEmail = true;
                break;
            }
        }
        return isRightEmail;
    }
}
